package services

import (
	"github.com/shirou/gopsutil/v3/cpu"
	"github.com/shirou/gopsutil/v3/disk"
	"github.com/shirou/gopsutil/v3/mem"
)

// SystemService 提供系统资源监控功能
type SystemService struct {
	scriptService *ScriptService
}

// NewSystemService 创建一个新的系统服务实例
func NewSystemService() *SystemService {
	return &SystemService{}
}

// GetSystemResources 获取系统资源使用情况
func (s *SystemService) GetSystemResources() (*SystemResources, error) {
	// 获取CPU使用率
	cpuPercent, err := cpu.Percent(0, false)
	if err != nil {
		return nil, err
	}

	// 获取内存使用情况
	memInfo, err := mem.VirtualMemory()
	if err != nil {
		return nil, err
	}

	// 获取磁盘使用情况
	diskInfo, err := disk.Usage("/")
	if err != nil {
		return nil, err
	}

	// 获取运行中的脚本数量
	runningScripts := 0
	if s.scriptService != nil {
		runningScripts = s.scriptService.GetRunningScripts()
	}

	return &SystemResources{
		CPU: CPUInfo{
			Percent: cpuPercent[0],
		},
		Memory: MemoryInfo{
			Total:   memInfo.Total,
			Used:    memInfo.Used,
			Percent: memInfo.UsedPercent,
		},
		Disk: DiskInfo{
			Total:   diskInfo.Total,
			Used:    diskInfo.Used,
			Percent: diskInfo.UsedPercent,
		},
		RunningScripts: runningScripts,
	}, nil
}

// SetScriptService 设置脚本服务实例
func (s *SystemService) SetScriptService(scriptService *ScriptService) {
	s.scriptService = scriptService
}

// SystemResources 系统资源信息
type SystemResources struct {
	CPU            CPUInfo    `json:"cpu"`
	Memory         MemoryInfo `json:"memory"`
	Disk           DiskInfo   `json:"disk"`
	RunningScripts int        `json:"running_scripts"`
}

// CPUInfo CPU信息
type CPUInfo struct {
	Percent float64 `json:"percent"`
}

// MemoryInfo 内存信息
type MemoryInfo struct {
	Total   uint64  `json:"total"`
	Used    uint64  `json:"used"`
	Percent float64 `json:"percent"`
}

// DiskInfo 磁盘信息
type DiskInfo struct {
	Total   uint64  `json:"total"`
	Used    uint64  `json:"used"`
	Percent float64 `json:"percent"`
}
